'use strict';

const Service = require('egg').Service;

class UserService extends Service {
  /**
   * 用户登陆注册相关
   */

  async findUserByPhoneAndPassword(data) {
    const user = await this.app.mysql.select('user', {
      where: {
        password: data.password,
        phone: data.phone,
      },
      columns: [
        'id',
        'username',
        'phone',
        'position',
        'introduction',
        'avatar_url',
        'theme_color',
        'dark_mode',
        'font_size',
        'role',
      ],
    });
    return user;
  }

  async addUser(data) {
    const res = await this.app.mysql.insert('user', {
      username: data.username,
      password: data.password,
      phone: data.phone,
    });
    const _id = res.insertId;
    return { _id };
  }

  /**
   * 用户信息设置相关
   */

  async findUserById(userId) {
    const user = await this.app.mysql.get('user', {
      id: userId,
    });
    return { user };
  }

  async updateUserInfo(user_id, data) {
    const options = {
      where: {
        id: user_id,
      },
    };
    const result = await this.app.mysql.update('user', data, options);
    const updateSuccess = result.affectedRows === 1;
    return { updateSuccess };
  }

  async updateUserSetting(user_id, data) {
    const options = {
      where: {
        id: user_id,
      },
    };
    const result = await this.app.mysql.update('user', data, options);
    const updateSuccess = result.affectedRows === 1;
    return { updateSuccess };
  }

  async updateUserPassword(user_id, data) {
    const options = {
      where: {
        id: user_id,
      },
    };
    const result = await this.app.mysql.update('user', data, options);
    const updateSuccess = result.affectedRows === 1;
    return { updateSuccess };
  }

  async getSign(userId) {
    const hasPerson = await this.app.mysql.get('user_sign', { user_id: userId });
    let today = 0;
    if (hasPerson) {
      const lastSign = await this.app.mysql.query(
        `SELECT MAX(date) as date FROM user_sign WHERE user_id = ${userId} GROUP BY user_id`
      );
      if (
        lastSign[0] &&
        lastSign[0].date &&
        lastSign[0].date.toLocaleDateString() === new Date().toLocaleDateString()
      ) {
        today = 1;
      }
    }
    return { today };
  }

  async sign(id) {
    let signSuccess = false;
    const { today } = await this.getSign(id);
    console.log(today);
    if (!today) {
      const result = await this.app.mysql.insert('user_sign', {
        user_id: id,
        date: new Date(),
      });
      signSuccess = result.affectedRows === 1;
    }
    return { signSuccess };
  }

  /**
   * 用户文章相关
   */

  async searchUserEssayList(userId) {
    const list = await this.app.mysql
      .query(`SELECT e.id, title, publish_time, e.introduction, name, username, avatar_url,
    (SELECT IFNULL(SUM(is_like),0) FROM essay_like WHERE e.id = essay_id) AS like_count,
    (SELECT IFNULL(SUM(is_collect),0) FROM essay_like WHERE e.id = essay_id) AS collect_count,
    (SELECT IFNULL(COUNT(content),0) FROM comment WHERE e.id = essay_id) AS comment_count,
    IFNULL((SELECT is_like FROM essay_like WHERE e.id = essay_id AND essay_like.user_id = ${userId}),0) AS is_like,
    IFNULL((SELECT is_collect FROM essay_like WHERE e.id = essay_id AND essay_like.user_id = ${userId}),0) AS is_collect
    FROM essay e, tab, user
    WHERE e.tab_id = tab.id AND e.publish_user_id = user.id AND is_publish = 1 AND e.publish_user_id = ${userId}`);
    return { list };
  }

  async essayCommentLike(userId) {
    const list = await this.app.mysql.query(
      `SELECT essay_id, title AS essay_title, comment_id, comment.content AS comment_content, is_like,
      (SELECT COUNT(is_like) FROM comment_like WHERE comment.id = comment_like.comment_id) AS comment_like_count,
      (SELECT COUNT(content) FROM comment WHERE essay_id = comment.id) AS comment_count
      FROM comment, comment_like, essay
      WHERE comment.id = comment_like.comment_id AND essay.id = comment.essay_id AND comment_like.user_id = ${userId} AND is_like = 1`
    );
    return { list };
  }

  async essayLike(userId) {
    const list = await this.app.mysql.query(
      `SELECT e.id, title, publish_time, e.introduction, name, username, avatar_url,
      (SELECT IFNULL(SUM(is_like),0) FROM essay_like WHERE e.id = essay_id) AS like_count,
      (SELECT IFNULL(SUM(is_collect),0) FROM essay_like WHERE e.id = essay_id) AS collect_count,
      (SELECT IFNULL(COUNT(content),0) FROM comment WHERE e.id = essay_id) AS comment_count,
      IFNULL((SELECT is_like FROM essay_like WHERE e.id = essay_id AND essay_like.user_id = ${userId}),0) AS is_like,
      IFNULL((SELECT is_collect FROM essay_like WHERE e.id = essay_id AND essay_like.user_id = ${userId}),0) AS is_collect
      FROM essay e, essay_like, tab, user
      WHERE e.tab_id = tab.id AND e.publish_user_id = user.id AND e.id = essay_like.essay_id AND user_id = ${userId} AND is_like = 1`
    );
    return { list };
  }

  async essayCollect(userId) {
    const list = await this.app.mysql
      .query(`SELECT e.id, title, publish_time, e.introduction, name, username, avatar_url,
      (SELECT IFNULL(SUM(is_like),0) FROM essay_like WHERE e.id = essay_id) AS like_count,
      (SELECT IFNULL(SUM(is_collect),0) FROM essay_like WHERE e.id = essay_id) AS collect_count,
      (SELECT IFNULL(COUNT(content),0) FROM comment WHERE e.id = essay_id) AS comment_count,
      IFNULL((SELECT is_like FROM essay_like WHERE e.id = essay_id AND essay_like.user_id = ${userId}),0) AS is_like,
      IFNULL((SELECT is_collect FROM essay_like WHERE e.id = essay_id AND essay_like.user_id = ${userId}),0) AS is_collect
      FROM essay e, essay_like, tab, user
      WHERE e.tab_id = tab.id AND e.publish_user_id = user.id AND e.id = essay_like.essay_id AND user_id = ${userId} AND is_collect = 1`);
    return { list };
  }

  /**
   * 用户力扣专区
   */

  async lcCollect(userId) {
    const list = await this.app.mysql.query(
      `SELECT id, url, title, passing_rate, level, 
      (SELECT SUM(is_like) FROM leetcode_like WHERE id = leetcode_id) AS like_count,
      (SELECT SUM(is_collect) FROM leetcode_like WHERE id = leetcode_id) AS collect_count
            FROM leetcode RIGHT JOIN leetcode_like ON id = leetcode_id 
            WHERE user_id = ${userId} AND is_collect = 1`
    );
    return { list };
  }

  async lcLike(userId) {
    const list = await this.app.mysql.query(
      `SELECT id, url, title, passing_rate, level, 
      (SELECT SUM(is_like) FROM leetcode_like WHERE id = leetcode_id) AS like_count,
      (SELECT SUM(is_collect) FROM leetcode_like WHERE id = leetcode_id) AS collect_count
      FROM leetcode RIGHT JOIN leetcode_like ON id = leetcode_id 
      WHERE user_id = ${userId} AND is_like = 1`
    );
    return { list };
  }

  /**
   * 用户话题相关
   */

  async getUserTopicList(userId) {
    const list = await this.app.mysql.query(`SELECT id, content, publish_time,
    ( SELECT COUNT( content ) FROM topic_comment WHERE topic.id = topic_id AND reply_comment_id = 0 ) AS comment_count
    FROM topic
    WHERE user_id = ${userId}`);
    return { list };
  }

  /**
   * 用户关注相关
   */

  async getFollowList(userId) {
    const list = await this.app.mysql.query(
      `SELECT id, username, position, introduction, avatar_url
      FROM user
      WHERE id IN (
        SELECT follower_id
        FROM user_follower, user
        WHERE user_follower.user_id = user.id AND user_id = ${userId}
      )`
    );
    return { list };
  }

  async getFollowedList(userId) {
    const list = await this.app.mysql.query(
      `SELECT id, username, position, introduction, avatar_url
      FROM user
      WHERE id IN (
        SELECT user_id
        FROM user_follower, user
        WHERE user_follower.user_id = user.id AND follower_id = ${userId}
      )`
    );
    return { list };
  }

  async followUser(followerId, userId) {
    const result = await this.app.mysql.insert('user_follower', {
      follower_id: followerId,
      user_id: userId,
    });
    const insertSuccess = result.affectedRows === 1;
    return { insertSuccess };
  }

  async cancelFollowTopic(followerId, userId) {
    const result = await this.app.mysql.delete('user_follower', {
      follower_id: followerId,
      user_id: userId,
    });
    const deleteSuccess = result.affectedRows === 1;
    return { deleteSuccess };
  }
}

module.exports = UserService;
